package com.atguigu.springcloud.compute;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@Slf4j
public class MyLB implements LoadBalancer{
    AtomicInteger atomicInteger=new AtomicInteger(0);
    /*
    * 获取到访问服务的次数,实际应用过程中肯定不是单线程操作,因此使用AtomicInteger
    * 使用CAS自旋锁
    * compareAndSet(current,next)
    * 比较主内存的值与期望值是否一样,相同则返回true,并设其值为next
    * */
    public int getIndexFor(){
        int current;
        int next;
        do {
            current = this.atomicInteger.get();
            next = current>=2147483647?0:current+1;
        } while(!this.atomicInteger.compareAndSet(current,next));
        log.info("这是第{}次访问",next);
        return next;
    }
    @Override
    public ServiceInstance getServices(List<ServiceInstance> instances) {
        int index;
        index=getIndexFor() % instances.size();
        return instances.get(index);
    }
}
